package org.ngrinder.demand.controller;

import org.ngrinder.common.constant.ControllerConstants;
import org.ngrinder.common.constants.GrinderConstants;
import org.ngrinder.model.Permission;
import org.ngrinder.model.Role;
import org.ngrinder.model.TestRequirement;
import org.ngrinder.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TestRequirementService extends AbstractTestRequirementService implements ControllerConstants, GrinderConstants {
	
	@Autowired
	private TestRequirementRepository testRequirementRepository;

	@Override
	@Transactional
	public TestRequirement save(User user,
			TestRequirement testRequirement) {
				
		return testRequirementRepository.saveAndFlush(testRequirement);
	}
	

	public Page<TestRequirement> getPagedAll(User user, Pageable pageable) {
		Specifications<TestRequirement> spec = Specifications.where(TestRequirementSpecification.idEmptyPredicate());
		
		if (user.getRole().equals(Role.USER)) {
			spec = spec.and(TestRequirementSpecification.createdBy(user));
		}
		
		return testRequirementRepository.findAll(spec, pageable);
	}
	
	@Override
	public TestRequirement getOne(Long id) {
		return testRequirementRepository.findOne(id);
	}
	
	@Transactional
	public void delete(User user, long id) {
		TestRequirement testRequirement = getOne(id);
		// If it's not requested by user who started job. It's wrong request.
		if (!hasPermission(testRequirement, user, Permission.DELETE_TEST_OF_OTHER)) {
			return;
		}
		
		testRequirementRepository.delete(testRequirement);
	}
	
	public boolean hasPermission(TestRequirement testRequirement, User user, Permission type) {
		return testRequirement != null && (user.getRole().hasPermission(type) || user.equals(testRequirement.getCreatedUser()));
	}

}
